/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-01-12 09:35:49
 * @LastEditTime : 2023-08-25 17:14:11
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Common\Api\index.jsx
 * @Description  :
 */
import axios from 'axios'
import { notification } from 'antd'
import { API_LIST } from './Api'
import qs from 'qs'

const apiList = API_LIST()

const TypeXFrom = [apiList['posToken'], apiList['posEzvizStart'], apiList['posEzvizStop'], apiList['posEzvizStop']]

const urlsToMatch = [
    apiList['getTokenByQRUuid'],
    apiList['getWeatherNow'],
    apiList['getGetOneBeamProduce'],
    'http://123.57.220.90:8909/project',
    apiList['posEzaddress'],
    apiList['posAIInteraction'],
    apiList['getWJHscreenRoadConsInsApi'],
    apiList['getWJHscreenPavRollApi'],
    apiList['getWJHspeedTemperatureList'],
    apiList['getWJHwarningAnalyse'],
    apiList['getWJHgetDeviceWorkDay'],
    apiList['getWJHwarningDay'],
    apiList['getWJHgetDeviceStatistics'],
    apiList['getWJHcompactorAnalyse'],
    apiList['getWJHwarning'],
    apiList['getWJHcompactorDay'],
]

// 默认设置
axios.defaults.timeout = 100000
// 添加请求拦截器
axios.interceptors.request.use(
    config => {
        const { url } = config
        if (TypeXFrom.includes(url)) {
            const newHeaders = Object.assign({}, config.headers, {
                'content-type': 'application/x-www-form-urlencoded',
            })
            config.headers = newHeaders
            return config
        } else {
            if (urlsToMatch.includes(url)) {
                const newHeaders = Object.assign({}, config.headers, {
                    'content-type': 'application/json; charset=utf-8',
                })
                config.headers = newHeaders
                return config
            } else {
                if (sessionStorage.getItem('TOKEN')) {
                    return {
                        ...config,
                        headers: {
                            ...config.headers,
                            'content-type': 'application/json; charset=utf-8',
                            Authorization: sessionStorage.getItem('TOKEN'),
                        },
                        paramsSerializer: params => qs.stringify(params, { arrayFormat: 'repeat' }),
                    }
                } else {
                    return Promise.reject({ message: '无效请求头' })
                }
            }
        }
    },
    error => Promise.reject(error),
)
// 添加响应拦截器
axios.interceptors.response.use(
    response => response,
    error => {
        if (error.response) {
            msag(error)
        } else if (error.request) {
            notification.error({
                message: '请求已经成功发起，但没有收到响应',
                description: error.request || '请联系管理员',
            })
        } else {
            notification.error({ message: '发送请求时出了点问题', description: error.message || '请联系管理员' })
        }
        return Promise.reject(error)
    },
)

export const Http = http => {
    if (!http) return false
    return new Promise((resolve, reject) => {
        const { url, data, path, headers } = http
        switch (url.substring(0, 3)) {
            case 'get':
                axios
                    .get(API_LIST(path)[url], { params: data, headers })
                    .then(res => resolve(res.data))
                    .catch(err => reject(err))
                break
            case 'pos':
                axios
                    .post(API_LIST(path)[url], data)
                    .then(res => resolve(res.data))
                    .catch(err => reject(err))
                break
            case 'pst':
                axios
                    .post(API_LIST(path)[url], {}, data)
                    .then(res => resolve(res.data))
                    .catch(err => reject(err))
                break
            case 'put':
                axios
                    .put(API_LIST(path)[url], data)
                    .then(res => resolve(res.data))
                    .catch(err => reject(err))
                break
            case 'del':
                axios
                    .delete(API_LIST(path)[url], data)
                    .then(res => resolve(res.data))
                    .catch(err => reject(err))
                break
            case 'pat':
                axios
                    .patch(API_LIST(path)[url], data)
                    .then(res => resolve(res.data))
                    .catch(err => reject(err))
                break
            default:
                return false
        }
    })
}

function getBlobContent(blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()

        reader.onload = () => {
            const content = reader.result
            resolve(content)
        }

        reader.onerror = () => {
            reader.abort()
            reject(new Error('无法读取 Blob 内容'))
        }

        reader.readAsText(blob)
    })
}

const msag = err => {
    switch (err.response.status) {
        case 400:
            if (err.response.data.error) {
                notification.error({
                    message: PermutationArray[err.response.data.error] || err.response.data.error,
                    description:
                        PermutationArray[err.response.data.error_description] || err.response.data.error_description,
                })
            } else {
                const typeOf = typeof err.response.data

                if (typeOf === 'string')
                    notification.error({
                        key: 'err400',
                        message: '操作失败!',
                        description: `原因:${err.response.data}`,
                    })
                else if (typeOf === 'object') {
                    if (err.response.data.code) {
                        notification.error({
                            key: 'err400',
                            message: '操作失败!',
                            description: `原因:${err.response.data.data}`,
                        })
                    } else {
                        getBlobContent(err.response.data)
                            .then(content => {
                                if (content.includes('data'))
                                    notification.error({
                                        key: 'err400',
                                        message: '操作失败!',
                                        description: `原因:${JSON.parse(content).data}`,
                                    })
                                else
                                    notification.error({
                                        key: 'err400',
                                        message: '操作失败!',
                                        description: `原因:${content}`,
                                    })
                            })
                            .catch(() => notification.error({ key: 'err400', message: '操作失败!' }))
                    }
                }
            }
            break
        case 401:
            console.log(err.response)
            break
        case 403:
            alert('拒绝访问')
            break
        case 404:
            alert('请求地址出错')
            break
        case 405:
            alert('方法不允许访问')
            break
        case 408:
            alert('请求超时')
            break
        case 500:
            console.log('[obje]', err.response.data)
            notification.error({
                key: 'err400',
                message: '操作失败!',
                description: `原因:${err.response.data.message}`,
            })

            // alert('服务器内部错误')
            break
        case 501:
            alert('服务未实现')
            break
        case 502:
            alert('网关错误')
            break
        case 503:
            alert('服务不可用')
            break
        case 504:
            alert('网关超时')
            break
        case 505:
            alert('HTTP版本不受支持')
            break
        case 520:
            alert('接口又爱了!')
            break
        default:
            return false
    }
}

const PermutationArray = {
    invalid_grant: '登录失败',
    invalid_username_or_password: '用户不存在或密码错误！',
}
